
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */
package com.hlkj.pay.app.common.ext.aliyun;

import cn.hutool.json.JSONObject;
import com.aliyun.ocr_api20210707.models.RecognizeBankCardResponse;
import com.aliyun.tea.TeaException;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.framework.extension.annotation.Extension;
import com.hlkj.pay.app.common.OcrExtPt;
import com.hlkj.pay.common.CommonResultCode;
import com.hlkj.pay.app.common.ext.CommonExtConstant;
import com.hlkj.pay.dto.common.ocr.OcrScan;
import com.hlkj.pay.dto.common.ocr.OcrScanCard;
import com.hlkj.pay.dto.common.ocr.OcrScanResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
/**
 * @author monk@techsun.com
 * @date 2023/04/13 11:58
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Extension(bizId = CommonExtConstant.CHANNEL_ALIYUN,useCase = CommonExtConstant.OCR_BANK_CARD)
public class AliyunOcrCardExtPt extends AliyunOcrCommonExtPt implements OcrExtPt {
    @Override
    public CommonResult<OcrScanResult> ocrScan(OcrScan ocrScan) {
		com.aliyun.ocr_api20210707.Client client = null;
		try {
			client = createClient(ocrScan.getOcrConfig());
		}
		catch (Exception error) {
			log.error("阿里云 银行卡 orc初始化失败：message",error.getMessage(),error);
			return CommonResult.error(CommonResultCode.OCR_INIT_ERROR.getCode(),error.getMessage());
		}
		com.aliyun.ocr_api20210707.models.RecognizeBankCardRequest recognizeBankCardRequest = new com.aliyun.ocr_api20210707.models.RecognizeBankCardRequest()
				.setUrl(ocrScan.getImageUrl());
		com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
		try {
			// 复制代码运行请自行打印 API 的返回值
			RecognizeBankCardResponse recognizeBankCardResponse = client.recognizeBankCardWithOptions(
					recognizeBankCardRequest, runtime);
			String bodyData = recognizeBankCardResponse.getBody().getData();
			JSONObject jsonObject=JsonUtils.parseObj(bodyData);
			JSONObject data = jsonObject.getJSONObject("data");
			if(data==null){
				return CommonResult.error(CommonResultCode.OCR_ERROR);
			}
			return CommonResult.success(JsonUtils.parseObject(data.toString(),
					OcrScanCard.class));
		} catch (TeaException error) {
			// 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
			// 错误 message
			log.error("阿里云 银行卡 orc识别失败：message",error.getMessage(),error);
			return CommonResult.error(CommonResultCode.OCR_ERROR.getCode(),error.getMessage());
		} catch (Exception _error) {
			TeaException error = new TeaException(_error.getMessage(), _error);
			// 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
			// 错误 message
			log.error("阿里云 银行卡 orc识别失败：message",error.getMessage(),_error);
			return CommonResult.error(CommonResultCode.OCR_ERROR.getCode(),error.getMessage());
		}
	}
}
